#include <stdio.h>
#include "kernel_list.h"
#include <stdlib.h>
#include <string.h>

struct student
{
    char name[20];
    int age;
    float score;
    struct list_head list;
};

struct student *createListNode(char *name, int age, float score)
{
    struct student *stu = malloc(sizeof(struct student));
    strcpy(stu->name, name);
    stu->age = age;
    stu->score = score;
    return stu;
}

struct student *initListHead()
{
    struct student *head = malloc(sizeof(struct student));
    INIT_LIST_HEAD(&head->list);
    return head;
}

// 尾部插入
void insertListNodeTail(struct student *head, struct student *node)
{
    list_add_tail(&node->list, &head->list);
}

// 遍历链表
void printList(struct student *head)
{
    struct student *pos;
    list_for_each_entry(pos, &head->list, list)
    {
        printf("name:%s age:%d score:%.2f\n", pos->name, pos->age, pos->score);
    }
}

// 查找年龄是 19的这个学生
struct student *findStudentByAge(struct student *head, int age)
{
    struct student *pos;
    list_for_each_entry(pos, &head->list, list)
    {
        if (pos->age == age)
        {
            return pos;
        }
    }
    return NULL;
}

struct student *findStudentByName(struct student *head, char *name)
{
    struct student *pos;
    list_for_each_entry(pos, &head->list, list)
    {
        if (strcmp(pos->name, name) == 0)
        {
            return pos;
        }
    }
    return NULL;
}

int main()
{

    // head是大结构体 链表头
    struct student *head = initListHead();

    // 尾插
    insertListNodeTail(head, createListNode("nick", 19, 99.9));
    insertListNodeTail(head, createListNode("mark", 18, 88.8));
    insertListNodeTail(head, createListNode("kimi", 17, 77.7));
    insertListNodeTail(head, createListNode("jim", 16, 66.6));

    // 头插
    list_add(&createListNode("nicholas", 20, 100)->list, &head->list);

    // 遍历
    printList(head);

    // 查找结点
    struct student *s1 = findStudentByAge(head, 19);
    printf("s1: %s %d %.1f\n", s1->name, s1->age, s1->score);

    // 删除节点
    list_del(&s1->list);
    free(s1);
    printf("删除节点后：\n");
    printList(head);

    struct student *s_jim = findStudentByName(head, "jim");
    struct student *s_kimi = findStudentByName(head, "kimi");
    printf("s_jim: %s %d %.1f\n", s_jim->name, s_jim->age, s_jim->score);
    printf("s_kimi: %s %d %.1f\n", s_kimi->name, s_kimi->age, s_kimi->score);
    // 移动链表节点
    list_move(&s_kimi->list, &s_jim->list);

    printf("移动节点后：\n");
    printList(head);

    printf("%d\n", list_empty(&head->list));

    return 0;
}
